import { GetHomeIndex, wachatLogin, isLogin } from '@/api'
import { setToken } from '@/utils/storage'

export const types = {
  SET_HOME_INDEX_LIST: 'setHomeIndexList',
  GET_HOME_INDEX_LIST: 'home/GetHomeIndexList',
  GET_AUTH_IS_LOGIN: 'home/AuthIsLogin',
  GET_AUTH_WACHAT_LOGIN: 'home/AuthWachatLogin'
}

export const actions = {
  getHomeIndexList(params: Object ) {
    return {
      type: types.GET_HOME_INDEX_LIST,
      params
    }
  },
  getAuthIsLogin() {
    console.log('getAuthIsLogin:')
    return {
      type: types.GET_AUTH_IS_LOGIN
    }
  },
  getAuthWachatLogin(payload: IPayload) {
    return {
      type: types.GET_AUTH_WACHAT_LOGIN,
      payload
    }
  }
}

export default {
  namespace: 'home',
  state: {
    bannerList: [],
    goodsList: [],
    total: 0,
    size: 10,
    userInfo: JSON.parse((localStorage as any).getItem('userInfo')) || {}
  },
  subscriptions: {
    // setup({ dispatch, history }) {  // eslint-disable-line
    // }
  },
  reducers: {
    setHomeIndexList(state:any, action:any) {
      // console.log(333)
      // console.log('action:', action)
      state.bannerList = action.result.data.banner
      state.total = action.result.data.goods.total
      state.goodsList = action.result.data.goods.data
      return {...state}
    },
    // 用户信息头像信息
    setAuthInfo(state:any, action: any) {
      // console.log("setAuthInfo:", action)
      // 设置用户信息，设置token
      state.userInfo = action.result.data;
      localStorage.setItem('userInfo', JSON.stringify(state.userInfo))
      setToken(action.result.data.token)
      return {...state}
    },
    // 登陆重定向接口
    setIsLogin(state:any, action:any) {
      // console.log("setIsLogin:", action)
      if (action.result.code === 0) {
        window.location.replace(`/api/user/wachatLogin?
        redirectUrl=${window.location.hostname}/home`)
      }
      return {...state}
    }
  },
  effects: {
    *GetHomeIndexList({ page = 0, size = 10 }: { page: number, size: number }, { call, put }: { call: any, put: any }) {
      let result = yield call(GetHomeIndex, { page, size })
      yield put({ type: types.SET_HOME_INDEX_LIST, result });
    },
    // 授权信息获取接口
    *AuthWachatLogin({ payload }: { payload: IPayload }, { call, put }: {call:any, put: any}) {
      // console.log('AuthWachatLogin: ', payload)
      let result = yield call(wachatLogin, { code: payload.code, state: payload.state })
      // console.log('result:', result)
      yield put({ type: 'setAuthInfo', result });
    },
    // 用户进入页面登陆重定向接口
    *AuthIsLogin({ payload }: { payload: any }, { call, put }: {call:any, put: any}) {
      console.log('我是islogin接口', '-----------------------------')
      let result = yield call(isLogin)
      console.log('result:', result)
      yield put({ type: 'setIsLogin', result });
    },
  },
};

interface IPayload {
  code: string,
  state: string
}
